package com.simen.myapplication.androidnetworkservicediscoverydemo

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.View
import com.simen.hellobytes.socket.UDPMultiSocket
import com.simen.hellobytes.socket.helper.MessageListener
import java.net.DatagramPacket
import java.net.NetworkInterface

class MultiSocketActivity : AppCompatActivity() {

    var server:UDPMultiSocket?=null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_multi_socket)
    }

    override fun onDestroy() {
        super.onDestroy()
        server?.closeImmediately()
    }

    fun listen(view: View) {
        Thread(){
            kotlin.run {
                server=UDPMultiSocket(group,port).apply {
                    messageListener=object: MessageListener<DatagramPacket>{
                        override fun onMessage(buf: ByteArray?, length: Int, clientInfo: DatagramPacket?): Int {
                            Log.i(TAG,"receive message(byte array)")
                            return MessageListener.DISCONNECT;
                        }

                        override fun onMessage(buf: String?, clientInfo: DatagramPacket?): Int {
                            Log.i(TAG,"receive message(string)")
                            return MessageListener.DISCONNECT;
                        }
                    }
                    listen()

                    Log.i(TAG,"server end")
                }
            }
        }.start()
    }

    companion object{
        private val TAG=MultiSocketActivity.javaClass.simpleName;
        private var group="239.9.9.9";
        private var port=5353;
    }

    fun send(view: View) {
        Thread(){
            kotlin.run {
                var send=UDPMultiSocket(group,port)

                send.messageBytes="hello,this come from android".toByteArray()

                send.sendMulticast()

                Log.i(TAG,"send complete")
            }
        }.start()
    }
}